package com.lntea.netty.im.handler;

import com.lntea.netty.im.packet.CreateGroupRequestPacket;
import com.lntea.netty.im.packet.CreateGroupResponsePacket;
import com.lntea.netty.im.packet.common.Session;
import com.lntea.netty.im.packet.common.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 创建群组请求handler
 */
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket packet) throws Exception {
        List<String> userIdList = packet.getUserIdList();
        String groupId = randomGroupId();

        // 创建Channel群组
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());
        SessionUtil.bindChannelGroup(groupId, channelGroup);

        List<String> userNameList = new ArrayList<>();
        // 遍历用户id对应的Channel，加入到群组
        for (String userId : userIdList) {
            Channel channel = SessionUtil.getChannel(userId);
            channelGroup.add(channel);

            userNameList.add(SessionUtil.getSession(channel).getUserName());
        }

        // 组装创建群组响应数据包
        CreateGroupResponsePacket respPacket = new CreateGroupResponsePacket();
        respPacket.setSuccess(true);
        respPacket.setGroupId(groupId);
        respPacket.setUserNameList(userNameList);

        // 发送给群成员
        channelGroup.writeAndFlush(respPacket);

        System.out.println(String.format("群创建成功，id[%s]", groupId));
        System.out.println(String.format("群成员为%s", userNameList));
    }

    /**
     * 随机生成群组id
     * @return
     */
    private String randomGroupId() {
        return "g" + new Random().nextInt(100);
    }
}
